﻿using IM.Easy.Core.Constants;
using IM.Easy.Core.Extensions;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.AppContext
{
    public interface IUserContext
    {
        /// <summary>
        /// 用户id
        /// </summary>
        long Id { get; }

        /// <summary>
        /// 登录名
        /// </summary>
        string UserName { get; }

        /// <summary>
        /// 昵称
        /// </summary>
        string NickName { get; }

        /// <summary>
        /// 如果是1，那么则为超级管理员
        /// </summary>
        bool IsSuperAdmin { get; }

        /// <summary>
        /// 是否为本地账户
        /// </summary>
        bool IsLocalAccount { get; }

        /// <summary>
        /// 账户提供商
        /// </summary>
        string Provider { get; }
    }

    /// <summary>
    /// 用户上下文
    /// </summary>
    public class UserContext : IUserContext
    {
        /// <summary>
        /// 用户id
        /// </summary>
        public long Id => GetUserId();

        /// <summary>
        /// 登录名
        /// </summary>
        public string UserName => GetUserName();

        /// <summary>
        /// 昵称
        /// </summary>
        public string NickName { get; set; }

        /// <summary>
        /// 账户提供商
        /// </summary>
        public string Provider
        {
            get
            {
                return httpContext.User.FindFirstValue(ClaimConstTypes.Provider);
            }
        }

        /// <summary>
        /// 是否为本地账户
        /// </summary>
        public bool IsLocalAccount
        {
            get
            {
                return (string.IsNullOrEmpty(Provider) || string.Equals(Provider, "Local"));
            }
        }

        /// <summary>
        /// 如果是1，那么则为超级管理员
        /// </summary>
        public bool IsSuperAdmin => Id == 1 && IsLocalAccount;

        private HttpContext httpContext { get; set; }


        public UserContext(IHttpContextAccessor httpContextAccessor)
        {
            httpContext = httpContextAccessor.HttpContext;
        }

        private long GetUserId()
        {
            return (httpContext.User.FindFirstValue(ClaimTypes.PrimarySid)
                  ?? httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier)).ToLong();
        }

        private string GetUserName()
        {
            return httpContext.User.FindFirstValue(ClaimTypes.Name);
        }
    }
}
